package com.mj.guoqi.dao;

import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.mj.guoqi.util.DBHelper;

/**
 * Dao基类
 * @author zhaominglei
 * @date 2015-8-15
 * 
 */
public class BaseDao {
	
	/**
	 * 获取记录数
	 */
	public int getCount(Context context, String tableName) {
		SQLiteDatabase db = DBHelper.getInstance(context).getReadableDatabase();
		Long count = null;
		Cursor cursor = null;
		try {
			cursor = db.rawQuery("select count(*) from "+tableName, null);
			if (cursor.moveToFirst()) {
				count = cursor.getLong(0);
			}
			cursor.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (!cursor.isClosed()) {
				cursor.close();
			}
			db.close();
		}
		return (count != null) ? count.intValue() : 0;
	}
	
	/**
	 * 保存
	 */
	public void save(Context context, String sql) {
		SQLiteDatabase db = DBHelper.getInstance(context).getWritableDatabase();
		try {
			db.execSQL(sql);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			db.close();
		}
	}
	
	/**
	 * 保存
	 */
	public void save(Context context, List<String> sqls) {
		SQLiteDatabase db = DBHelper.getInstance(context).getWritableDatabase();
		db.beginTransaction();
		try {
			for (String sql : sqls) {
				db.execSQL(sql);
			}
			db.setTransactionSuccessful();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			db.endTransaction();
			db.close();
		}
	}
	
	/**
	 * 清空表
	 */
	public void deleteAll(Context context, String tableName) {
		SQLiteDatabase  db = DBHelper.getInstance(context).getWritableDatabase();
		try {
			db.execSQL("delete from "+tableName);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			db.close();
		}
	}
}
